package com.zhoug.common.chain;

import java.util.List;

import androidx.annotation.NonNull;

/**
 * 责任链的实现
 * @Author 35574
 * @Date 2021/4/9
 * @Description
 */
public class RealInterceptorChain<REQUEST extends IRequest,RESPONSE extends IResponse> implements Interceptor.Chain<REQUEST,RESPONSE> {
    /**
     * 拦截器集合
     */
    private final  List<? extends Interceptor<REQUEST,RESPONSE>> interceptors;
    /**
     * 当前拦截器在集合中的下标
     */
    private final int index;
    /**
     * 请求
     */
    private final REQUEST request;

    public RealInterceptorChain(@NonNull List<? extends Interceptor<REQUEST, RESPONSE>> interceptors, int index,@NonNull  REQUEST request) {
        this.interceptors = interceptors;
        this.index = index;
        this.request = request;
    }


    @Override
    public REQUEST request() {
        return request;
    }

    /**
     * 请求向下传递
     * @param request
     * @return
     */
    @Override
    public RESPONSE proceed(REQUEST request) {
        if (index >= interceptors.size()) throw new IndexOutOfBoundsException();
        //取出当前拦截器
        Interceptor<REQUEST, RESPONSE> interceptor = interceptors.get(index);
        //下一个处理者
        RealInterceptorChain<REQUEST, RESPONSE> next=new RealInterceptorChain<>(interceptors,index+1,request);
        //执行当前拦截器的拦截操作
        return interceptor.intercept(next);
    }


}
